package com.zuozhj.controller;

import java.util.UUID;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.Producer;
import com.zuozhj.common.Result;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.map.MapUtil;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


@RestController
public class CaptchaController extends BaseController {
    
    @Autowired
    Producer producer;

    @RequestMapping("/captcha")
    public Result captcha() throws IOException  {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();

        key = "aaaaa";
        code = "111111";

        BufferedImage image = producer.createImage(code);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        Base64Encoder encoder = new Base64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());

        redisUtil.hset("captcha", key, code, 120);

        return Result.success(
            MapUtil.builder()
                .put("key", key)
                .put("code", code)
                .put("captchaImg", base64Img)
                .build()
        );
    }
}
